  const handleEachMatch = async (matches, data) => {

    prn('matches', matches)
    if (matches) {
      for (let match of matches) {
        match = match.replace(/{{/, '')
        match = match.replace(/}}/, '')
        const match_var = match
        match = match.replace(/prompt_/, '')

        let pt = await db.prompts.get(+match)

        if(pt) {
          data[match_var] = pt.content
        }      
      }
    }

    return data
  }

  const addData = async (data, tpl) => {
    const regex = /\{\{prompt_\d+\}\}/g;
    const matches = tpl.match(regex);

    data = await handleEachMatch(matches, data)
    // prn('data',  data)

    return data
  }

 export const buildTplWithValues = async (prompt, props)=>{
      
      let tpl = prompt.content
      let data = props

      data = await addData(data, tpl)
  
      const ret = $.template(tpl, data)


      return ret;
  }


  const buildTpl = async ()=>{
      let ret = await buildTplWithValues()
      onTplOk(ret)
  }



const get_pt = async (id) => {
	return await db.prompts.get(id)
}

const parse_json = (rawString)=>{
	// 1. 去掉开头的 \`\`\`json 和结尾的 \`\`\`
	const jsonString = rawString
	  .replace(/^```json\s*/, '')  // 去掉开头的标记
	  .replace(/\s*```$/, '')       // 去掉结尾的标记
	  .trim();                      // 去除首尾空格

	// 2. 解析为 JSON
	try {
	  const data = JSON.parse(jsonString);
	  console.log("解析成功:", data);
	  return data
	} catch (error) {
	  console.error("解析失败:", error);
	}	

}


  const get_idea_fmt = async (id) => {
    // prn(idea)
  	const idea = await db.topic_ideas.get(id);

    let ret = `
      名称：${idea.title}
      描述：${idea.description}
      类型：${idea.genre}
    `
    // prn(ret)
    return ret
  }


//生成选题思路
export const genTopicIdea = async (id, props) => {
    let pt = await get_pt(id)
    prn('genTopicIdea lib')

    let ret = await buildTplWithValues(pt, props)

    ret += `
# 输出格式示例：
'''
    "title": "",
    "description": "",
    "genre": ""
'''    
    `

    ret = await $.callGlmAPI(ret)

    return parse_json(ret)

}


//生成大纲
export const genOutline = async (id, outlinept_id) => {
    let idea_str = await get_idea_fmt(id)

    prn('genOutline lib')
    // prn(idea_str)

    let pt = await get_pt(outlinept_id)
    let props = {'idea': idea_str}
    let ret = await buildTplWithValues(pt, props)

    ret = await $.callGlmAPI(ret)
    prn(ret)
    return ret
}


export const get_gen_plot_prompt = async (id, outline_id, require_id) => {
    let pt = await get_pt(id)
    let pt_outline = await db.outlines.get(outline_id)
    let pt_write_require = await get_pt(require_id)

    
    let props = {'outline': pt_outline.content, 'write_require': pt_write_require.content}
    let ret = await buildTplWithValues(pt, props)

    return ret	
}

//生成情节
export const genPlot = async (id, outline_id, require_id) => {

	let ret = await get_gen_plot_prompt(id, outline_id, require_id)

	prn(ret)

    // let llm_ret = await $.callGlmAPI(ret)

    // prn(llm_ret)

    // return llm_ret
}
